package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;

    public void delete(Long id) {

        //先删除角色与权限的关系
        mapper.deleteRolePermissionRelation(id);
        //再删除角色自己

        mapper.deleteByPrimaryKey(id);
    }

    public void save(Role record) {
        mapper.insert(record);

        //获取权限对象
        List<Permission> permissions = record.getPermissions();
        if (permissions != null){
            for (Permission permission : permissions){
                //维护角色与权限的关系
                mapper.saveRolePermissionRelation(record.getId(), permission.getId());
            }
        }

    }

    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Role> list() {
        return mapper.selectAll();
    }

    public void update(Role record) {
        mapper.updateByPrimaryKey(record);

        //先删除角色与权限的关系
        mapper.deleteRolePermissionRelation(record.getId());
        List<Permission> permissions = record.getPermissions();
        if (permissions != null){
            for (Permission permission : permissions){
                //再维护角色与权限的关系
                mapper.saveRolePermissionRelation(record.getId(), permission.getId());
            }
        }

    }

    //分页
    public PageResult query(QueryObject qo){
        int count = mapper.queryForCount(qo);
        List<Role> list = mapper.queryForList(qo);
        if (count==0){
            return new PageResult();
        }
        return new PageResult(count,list);
    }


    //根据员工id查询所有角色id
    public List<Long> queryRoleIdByEmpId(Long empId){
        return mapper.queryRoleIdByEmpId(empId);
    }

    public List<String> queryRoleSnByEmpId(Long id) {
        return mapper.queryRoleSnByEmpId(id);
    }

}
